package com.example.cardgame

import android.nfc.Tag
import android.util.Log
import java.io.Serializable

class CardMatchingGame(val count: Int): Serializable {
    var score = 0
        private set

    val cards: MutableList<Card>

    init {
        val deck = Deck()
        cards= mutableListOf()
        for (i in 1..count) {
            val card: Card? = deck.drawRandomCard()
            if (card != null) {
                cards.add(card)
            }
        }
    }
    fun reset(){
        val deck = Deck()
        cards.clear()
        for (i in 1..count) {
            val card: Card? = deck.drawRandomCard()
            if (card != null) {
                cards.add(card)
            }
        }
        score=0
    }
    fun cardAtIndex(index: Int): Card {
        return cards.get(index)
    }
    var i=0
    var j=0
    val MISMATCH_PENALTY = 3
    val MATCH_BONUS = 4
    val COST_TO_CHOOSE = 1

    fun chooseCardAtIndex(index: Int) {
        val card= cardAtIndex(index)
        if (!card.isMatched) {
            if (card.isChosen) {
                card.isChosen = false
            } else {
                for (otherCard in cards) {
                    i++
                    if(otherCard.isChosen && !otherCard.isMatched ){
                        for(otherCard2 in cards){
                            j++
                            if(otherCard2.isChosen &&!otherCard2.isMatched &&i!=j){
                                val matchScore=card.match(arrayOf(otherCard,otherCard2))
                                if(matchScore>0){
                                    score+=matchScore*MATCH_BONUS
                                    otherCard.isMatched=true
                                    otherCard2.isMatched=true
                                    card.isMatched=true
                                }else{
                                    score-=MISMATCH_PENALTY
                                    otherCard.isChosen=false
                                    otherCard2.isChosen=false
                                }
                                break
                            }
                        }
                        j=0
                        break
                    }
                }
                i=0
                score-=COST_TO_CHOOSE
                card.isChosen=true
            }
        }
    }
}